'use strict';

import { platform_mechantcase_recordModel } from "../model/platform_mechantcase_record";
import { ServiceBase, Exceptions } from '../kalend';
import { merchantService } from "./merchant";
import { merchantcashService } from "./merchantcash";
import * as underscore from 'underscore';
import { common } from "../middleware/common";
import { platform_userService } from "./platform_user";
import { merchantwepaysetService } from "./merchantwepayset";
class platform_mechantcase_record extends ServiceBase {
    constructor() {
        super(platform_mechantcase_recordModel)
    }

    //分页查询提现记录
    async querybypage(params: any) {
        const offset = params.offset;
        const limit = params.limit;
        const starttime = params.sdate;
        const endtime = params.edate;
        const auditstatus = params.auditstatus;
        const uid = params.userid;
        const filter: any = {};

        if (uid) {
            let merchants: any = await merchantService.queryByUserId({
                userid: uid
            });
            let ids = underscore.pluck(merchants.rows, '_id');
            filter.merchantid = { '$in': ids };
        }


        if (starttime) {
            filter.updateTime = { '$gte': new Date(starttime) };
        }
        if (endtime) {
            if (filter.updateTime) {
                filter.updateTime['$lte'] = new Date(endtime);
            } else {
                filter.updateTime = { '$lte': new Date(endtime) };
            }
        }

        if (auditstatus) {
            filter.auditstatus = auditstatus;
        }

        let result:any = await super.queryPagination(offset, limit, {
            filter: filter
        });

        result.rows = result.rows.map((item:any) => {
            if (item.AuditStatus == 0) {
                item.AuditStatus = "审核中";
            } else if (item.AuditStatus == 1) {
                item.AuditStatus = "已审核";
            } else if (item.AuditStatus == 2) {
                item.AuditStatus = "审核拒绝";
            }else if(item.AuditStatus == 3){
              item.AuditStatus == "系统故障"
            }
            if (item.casestatus == 0) {
                item.casestatus = "未打款";
            } else {
                item.casestatus = "已打款";
            }
            return item;
        });

        const dataall = await this.queryAll({ filter: filter });
        let moneytotal = 0;
        let mealtotal = 0;
        let vitertotal = 0;
        dataall.map((a) => {
            if (a.type === '餐费账户') {
                moneytotal = common.add(moneytotal, a.totalcase);
            } else if (a.type === '餐币账户') {
                mealtotal = common.add(mealtotal, a.totalcase);
            } else if (a.type === '招募账户') {
                vitertotal = common.add(vitertotal, a.totalcase);
            }
        })
        result.footTotal = `共计 提现餐费账户【${moneytotal || 0}】元，餐币账户【${mealtotal || 0}】元，招募账户【${vitertotal}】元`;
        return result;
    }

    //创建提现记录
    async craeterecord(doc: any) {
      //验证手机短信
      
        let nocases: any =await this.queryAll({
            filter: {
                casestatus: 0,AuditStatus:1,merchantid: doc.merchantid
            }
        });

        if (nocases.length > 0) {
            return "存在审核通过未打款提现记录,审核通过并且打款后可进行提现申请";
        }
        let noaudits: any =await this.queryAll({
          filter: {
              AuditStatus:0,merchantid: doc.merchantid
          }
        });

        if (noaudits.length > 0) {
          return "存在未审核提现记录记录,审核通过并且打款后可进行提现申请";
      }

        if (doc.merchantid) {
         
            doc.partner_trade_no=this.genid();
            doc.payment_no='';
            doc.payment_time=''
            if(!doc.totalcase||!doc.merchantname||
              !doc.cashchannel||!doc.userrealname
              ||!doc.type){
            return "必填验证字段未通过";
            }
            if(doc.cashchannel=="wechat"&&!doc.wechatopenid&&!doc.wechatphone){
              return "微信必填验证字段未通过";
            }

            //验证传入打款账户是否属于当前商户
          let merchatpay:any=await  merchantwepaysetService.exist({wechatphone:doc.wechatphone,wechatopenid:doc.wechatopenid,
              wechatrealname:doc.userrealname,merchantname:doc.merchantname});
             if(!merchatpay){
              return "打款账户是不属于当前商户";
             } 

            await this.create(doc);
            let merdata = await merchantService.queryById(doc.merchantid);
            if (doc.type === '餐费账户') {
                let sy = common.sub(merdata.balance, Number(doc.totalcase));
                await merchantService.update(doc.merchantid, { balance: sy });
            } else if (doc.type === '招募账户' && merdata.legaluserid) {
                let puser = await platform_userService.queryById(merdata.legaluserid);
                let sy = common.sub(puser.balance, Number(doc.totalcase));
                await platform_userService.update(puser._id, { balance: sy });
            } else if (doc.type === '餐币账户') {
                let sy = common.sub(merdata.mealbalance, Number(doc.totalcase));
                await merchantService.update(doc.merchantid, { mealbalance: sy });
            }
            return "提现申请成功，请等待管理员审核";
        }

    }

    //生成提现订单号
    genid(){
        const now = new Date()
        const year = now.getFullYear();
        let month = now.getMonth() + 1;
        let day = now.getDate();
        let hour = now.getHours();
        let minutes = now.getMinutes();
        let seconds = now.getSeconds();
        String(month).length < 2 ? (month = Number("0" + month)) : month;
        String(day).length < 2 ? (day = Number("0" + day)) : day;
        String(hour).length < 2 ? (hour = Number("0" + hour)) : hour;
        String(minutes).length < 2 ? (minutes = Number("0" + minutes)) : minutes;
        String(seconds).length < 2 ? (seconds = Number("0" + seconds)) : seconds;
        const yyyyMMddHHmmss = `${year}${month}${day}${hour}${minutes}${seconds}`;
        return yyyyMMddHHmmss  +(Math.round(Math.random() * 1000000)).toString();
      }
    //提现审核
    async audit(pars: any) {
        const asta = pars.AuditStatus;
        const csta = pars.cashstatus;
        let doc: any = await this.querySingle({ _id: pars._id });
        if (asta) {
            if (doc.AuditStatus == 0) {
                //通过
                if (pars.AuditStatus == 1) {
                //调用付款
                var pres= await  merchantcashService.merchantcashpay({
                  partner_trade_no:doc.partner_trade_no,
                  openid:doc.wechatopenid,
                  wechatrealname:doc.userrealname,
                  amount: Number(doc.totalcase)*100,
                  desc:doc.merchantname+doc.type+'提现',
                });
                if(pres.return_code=="SUCCESS"){

                  if(pres.result_code=="SUCCESS"){
                  //付款成功,更新微信订单号，更新审核状态和打款状态
                  await this.update(pars._id,{payment_no:pres.payment_no,payment_time:pres.payment_time,AuditStatus:1,casestatus:1});
                  }

                  if(pres.result_code=="FAIL"){
                     //付款失败,退回金额，更新审核状态,回退金额
                  let merdata = await merchantService.queryById(doc.merchantid);
                  if (doc.type === '餐费账户') {
                      let sy = common.add(merdata.balance, Number(doc.totalcase));
                      await merchantService.update(doc.merchantid, { balance: sy });
                  } else if (doc.type === '招募账户' && merdata.legaluserid) {
                      let puser = await platform_userService.queryById(merdata.legaluserid);
                      let sy = common.add(puser.balance, Number(doc.totalcase));
                      await platform_userService.update(puser._id, { balance: sy });
                  } else if (doc.type === '餐币账户') {
                      let sy = common.add(merdata.mealbalance, Number(doc.totalcase));
                      await merchantService.update(doc.merchantid, { mealbalance: sy });
                  }
                  return this.update(pars._id, { AuditStatus: 3,wepayerrormsg:pres.return_msg});
                  }
                   
                }

                if(pres.return_code=="FAIL"){
                  //付款失败,退回金额，更新审核状态,回退金额
                  let merdata = await merchantService.queryById(doc.merchantid);
                  if (doc.type === '餐费账户') {
                      let sy = common.add(merdata.balance, Number(doc.totalcase));
                      await merchantService.update(doc.merchantid, { balance: sy });
                  } else if (doc.type === '招募账户' && merdata.legaluserid) {
                      let puser = await platform_userService.queryById(merdata.legaluserid);
                      let sy = common.add(puser.balance, Number(doc.totalcase));
                      await platform_userService.update(puser._id, { balance: sy });
                  } else if (doc.type === '餐币账户') {
                      let sy = common.add(merdata.mealbalance, Number(doc.totalcase));
                      await merchantService.update(doc.merchantid, { mealbalance: sy });
                  }
                  return this.update(pars._id, { AuditStatus: 3,wepayerrormsg:pres.return_msg});
                }



                } else if (pars.AuditStatus == 2) {
                    // 拒绝
                    let merdata = await merchantService.queryById(doc.merchantid);
                    if (doc.type === '餐费账户') {
                        let sy = common.add(merdata.balance, Number(doc.totalcase));
                        await merchantService.update(doc.merchantid, { balance: sy });
                    } else if (doc.type === '招募账户' && merdata.legaluserid) {
                        let puser = await platform_userService.queryById(merdata.legaluserid);
                        let sy = common.add(puser.balance, Number(doc.totalcase));
                        await platform_userService.update(puser._id, { balance: sy });
                    } else if (doc.type === '餐币账户') {
                        let sy = common.add(merdata.mealbalance, Number(doc.totalcase));
                        await merchantService.update(doc.merchantid, { mealbalance: sy });
                    }
                    return this.update(pars._id, { AuditStatus: pars.AuditStatus });
                }
                
            }
        }

        // if (csta) {
        //     if (doc.AuditStatus == 1 && doc.casestatus == 0) {
        //         // let merchant: any = await merchantService.querySingle({ _id: one.merchantid });
        //         // //let sy=merchant.balance-one.totalcase;
        //         // if (one.type === '餐厅账户') {
        //         //     let sy = common.sub(merchant.balance, one.totalcase)
        //         //     await merchantService.update(one.merchantid, { balance: sy });
        //         // } else if (one.type === '招募账户') {
        //         //     if (merchant.legaluserid) {
        //         //         let data = await platform_userService.queryById(merchant.legaluserid);
        //         //         let sy = common.sub(data.balance, one.totalcase)
        //         //         await platform_userService.update(merchant.legaluserid, { balance: sy });
        //         //     }
        //         // }

        //         return this.update(pars._id, { casestatus: csta });
        //     }
        // }

    }
    async querynoaudit(doc: any) {
        this.queryAll({
            filter: {
                casestatus: 0
            }
        });
    }
}

export const platform_mechantcase_record_Service = new platform_mechantcase_record();